#include"Doubly Linked List.h"
ListNode* ListInit()//初始化
{
	ListNode* newNode = BuyListNode(0);
	newNode->next = newNode;
	newNode->prev = newNode;
	return newNode;
}

ListNode* BuyListNode(SLDataType x)//申请新节点
{
	ListNode* Node = (ListNode*)malloc(sizeof(ListNode));
	Node->next = NULL;
	Node->prev = NULL;
	Node->val = x;
	return Node;
}

void ListPrint(ListNode* plist)//打印
{
	assert(plist);
	ListNode* cur = plist->next;
	while (plist != cur)
	{
		printf("%d ", cur->val);
		cur = cur->next;
	}
}

void ListPushBack(ListNode* plist, SLDataType x)//尾插
{
	assert(plist);
	//找到尾
	ListNode* tail = plist->prev;
	ListNode* newhead = BuyListNode(x);
	tail->next = newhead;
	newhead->prev = tail;
	plist->prev = newhead;
	newhead->next = plist;
}

void ListPopBack(ListNode* plist)//尾删
{
	assert(plist);
	assert(plist->next != plist);
	ListNode* tail = plist->prev;
	ListNode* prevtail = tail->prev;
	prevtail->next = plist;
	plist->prev = prevtail;
	free(tail);
}

void ListPushFront(ListNode* plist, SLDataType x)//头插
{
	assert(plist);
	ListNode* headNode = BuyListNode(x);
	ListNode* first = plist->next;//记录尾部
	plist->next = headNode;
	headNode->prev = plist;
	headNode->next = first;
	first->prev = headNode;
}
void ListPopFront(ListNode* plist)//头删
{
	assert(plist);
	assert(plist != plist->next);
	ListNode* first = plist->next;
	ListNode* second = first->next;
	plist->next = second;
	second->prev = plist;
	free(first);
}

ListNode* ListFind(ListNode* plist, SLDataType x)//查找
{
	assert(plist);
	ListNode* cur = plist->next;
	while (cur != plist)
	{
		if (cur->val == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, SLDataType x)//在pos之前插入
{
	assert(pos);
	ListNode* prev = pos->prev;
	ListNode* newNode = BuyListNode(x);
	newNode->next = pos;
	newNode->prev = prev;
	prev->next = newNode;
	pos->prev = newNode;
}
void ListErase(ListNode* pos)//删除pos处的节点
{
	assert(pos);
	//assert(pos != plist);//不允许删除头
	ListNode* prev = pos->prev;
	ListNode* next = pos->next;
	prev->next = next;
	next->prev = prev;
	free(pos);
}

void ListDestroy(ListNode** pplist)
{

	//销毁
	assert(*pplist);
	ListClear(*pplist);
	free(*pplist);
	*pplist = NULL;
}

void ListClear(ListNode* plist)
{
	assert(plist);
	ListNode* cur = plist->next;
	while (plist != cur)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	plist->next = plist;
	plist->prev = plist;
}